import * as T from './types';
import actions from './actions';
import React, {Component} from 'react';
import Taro from '@tarojs/taro';
// import WMLoading from '@/pages/common/loading';
import {connect} from 'react-redux';
import {Image, RichText, ScrollView, Text, View} from '@tarojs/components';

import {store2Props} from './selectors';
// import { WMkit } from 'wmkit';
import GetPrizes from './components/getPrizes';
import './index.less';
import api from 'api';
import bg2 from '@/assets/image/rouletteGame/bg2.png';
import bgTitle from '@/assets/image/rouletteGame/bgTitle.png';
import rouletteBg from '@/assets/image/rouletteGame/zpBg.png';
import btn1 from '@/assets/image/rouletteGame/btn1.png';
import btn2 from '@/assets/image/rouletteGame/btn2.png';
import btn3 from '@/assets/image/rouletteGame/btn3.png';
import btn4 from '@/assets/image/rouletteGame/btn4.png';

const durationTime = 2500; //旋转动画持续时间
let a = Taro.createAnimation({
  duration: durationTime, // 动画持续时间
  timingFunction: 'ease', // 动画时间函数
  delay: 0, // 延迟时间
});
actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      rotationAngle: 0,
      active: '',
      displayedAnnouncements: [], // 用于展示的中奖公告列表
      beginNum: 0,
      endNum: 3,
      myAnimation: a.export(),
      stopClick: false,
      bbb: 0,
    };
  }

  componentDidShow() {
    // const params = Taro.getCurrentInstance()?.router?.params;
    this.props.actions.init();
  }
  componentDidUpdate(prevProps) {
    let {
      main: {winningAnnouncementList},
    } = this.props;
    let {
      main: {winningAnnouncementList: prevWinningAnnouncementList},
    } = prevProps;

    // 检查前后 props 是否有变化
    if (winningAnnouncementList !== prevWinningAnnouncementList) {
      if (winningAnnouncementList.length) {
        this.updateDisplayedAnnouncements();
      }
    }
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  updateDisplayedAnnouncements() {
    let {
      main: {winningAnnouncementList},
    } = this.props;
    const {beginNum, endNum} = this.state;
    if (winningAnnouncementList.length) {
      const displayedAnnouncements = winningAnnouncementList.slice(beginNum, endNum);
      this.setState({displayedAnnouncements}, () => {
        // 每隔5秒更新一次中奖公告
        console.log('displayedAnnouncements====', winningAnnouncementList.length);

        let timer = setTimeout(() => {
          clearTimeout(timer);
          let newBeginNum = beginNum + 3; // 每次增加3条中奖公告
          let newEndNum = endNum + 3;

          if (newEndNum > winningAnnouncementList.length) {
            // 如果超过了中奖公告列表的长度，从头开始
            newBeginNum = 0;
            newEndNum = 3;
          }

          this.setState({
            beginNum: newBeginNum,
            endNum: newEndNum,
          });

          this.updateDisplayedAnnouncements(); //调用更新公告
        }, 5000); // 5秒钟更新一次
      });
    }
  }

  rotateToTargetAngle = (targetAngle) => {
    const {myAnimation, rotationAngle} = this.state;

    a = Taro.createAnimation({
      duration: durationTime, // 动画持续时间
      timingFunction: 'ease', // 动画时间函数
      delay: 0, // 延迟时间
    });
    // 配置动画效果
    a.rotate(targetAngle).step();
    console.log('jia==rotationAngle====', rotationAngle);
    // 更新组件状态，将新的动画应用到 DOM 元素
    this.setState(
      {
        myAnimation: a.export(),
        // rotationAngle: targetAngle
      },
      () => {
        console.log('jia====', targetAngle, this.state.rotationAngle);
      },
    );
  };

  playGames = async () => {
    // 否则触发新的动画
    this.setState(
      {
        stopClick: true,
        bbb: this.state.bbb + 1080,
      },
      async () => {
        await this.rotateToTargetAngle(this.state.bbb);
        // await this.animateRotation(this.state.rotationAngle + 720, 2500);
        // await this.speedUp();
        setTimeout(async () => {
          await this.speeddown2();
        }, 2500);
      },
    );
  };

  speeddown2 = async () => {
    const {animation, rotationAngle} = this.state;

    // await this.props.actions.action.goToTheLottery();
    let activeId;
    this.setState(
      {
        stopClick: true,
        bbb: this.state.bbb + 1080,
      },
      async () => {
        try {
          let params = {
            turntableActivityId: 1,
          };
          const res = await api.PrizesController.goToTheLotteryApi();
          console.log('抽奖======', res);
          if (res.code == 'K-000000') {
            activeId = res.context.createPrizeId;
            //0商品，1优惠券，2积分，3谢谢参与，4再来一次
            if (res.context.prizeType != null) {
              this.props.actions.action.commonChange('main.getPrizesInfo', res.context);
              if (res.context.prizeType == 1 || res.context.prizeType == 2) {
                setTimeout(() => {
                  this.props.actions.action.commonChange('main.getPrizesModel', true);
                }, 3000);
              } else if (res.context.prizeType == 0) {
                setTimeout(() => {
                  this.props.actions.action.commonChange('main.addAddressModel', true);
                }, 3000);
              } else if (res.context.prizeType == 3) {
                setTimeout(() => {
                  Taro.showToast({
                    title: '谢谢参与',
                    icon: 'none',
                  });
                }, 3000);
              } else if (res.context.prizeType == 4) {
                setTimeout(() => {
                  Taro.showToast({
                    title: '再来一次',
                    icon: 'none',
                  });
                }, 3000);
              }
            }
          } else {
            this.setState({
              stopClick: true,
            });
          }
        } catch (e) {
          console.log('去抽奖==e===', e);
          this.setState({
            stopClick: true,
          });
        }
        let {
          main: {prizesItemList},
        } = this.props;
        console.log('active===', this.state.active);
        const index = prizesItemList.findIndex((item) => item.createPrizeId == activeId);
        console.log('index----', index);
        if (index !== -1) {
          console.log(`'${activeId}' 在数组中的下标是: ${index}`);
          const itemAngle = 360 / prizesItemList.length;
          let indexAngle = itemAngle * index;
          await this.rotateToTargetAngle(-indexAngle + 25 + 360 + this.state.bbb);
        } else {
          await this.rotateToTargetAngle(0);
        }
        setTimeout(() => {
          this.setState(
            {
              active: activeId,
              stopClick: false,
            },
            () => {
              this.props.actions.action.prizesItem();
              this.props.actions.action.getWinningAnnouncement();
            },
          );
        }, durationTime);
      },
    );
  };
  render() {
    const {rotationAngle, active, displayedAnnouncements, myAnimation, stopClick} = this.state;
    let {
      main: {prizesItemList, frequencyNum, activityRegulation, winningAnnouncementList},
    } = this.props;
    // 计算每个抽奖项的角度间隔
    const itemAngle = 360 / prizesItemList.length;
    return (
      <View className="packageCRouletteGame">
        <Image className="bg" src={bg2} mode="widthFix" />
        <ScrollView scrollY>
          <View className="imgBox">
            <Image className="bgTitle" src={bgTitle} mode="widthFix" />
          </View>
          <View className="rouletteBox">
            <Image className="rouletteBg" src={rouletteBg} mode="widthFix" />
            <View className="roulette">
              {/* <View className="rouletteCon" animation={myAnimation} > */}
              <View className="rouletteCon" animation={myAnimation} style={`transform: rotate(${rotationAngle}deg);`}>
                {prizesItemList.length &&
                  prizesItemList.map((item, index) => {
                    return (
                      <View
                        // className="rouletteCon-item"
                        className={`rouletteCon-item ${active == item.createPrizeId ? 'active' : ''}`}
                        style={`transform: rotate(${itemAngle * index}deg);`}
                        key={index}
                      >
                        <View className="a">
                          <Text>{item.prizeName}</Text>
                          <Image className="rouletteImg" src={item.imagePrize} mode="heightFix" />
                        </View>
                      </View>
                    );
                  })}
              </View>
              <View className="rouletteBtn">
                <Image className="btn1" src={btn1} mode="heightFix" />
                <Image
                  className="btn2"
                  src={!stopClick && frequencyNum && prizesItemList.length > 0 ? btn2 : btn4}
                  mode="heightFix"
                  onClick={() => {
                    // console.log('1111111111');
                    this.setState(
                      {
                        active: '',
                      },
                      () => {
                        if (stopClick) {
                          return;
                        } else if (frequencyNum == 0) {
                          Taro.showToast({
                            title: '暂无抽奖次数',
                            icon: 'error',
                          });
                        } else if (prizesItemList.length <= 0) {
                          Taro.showToast({
                            title: '抽奖活动暂未开启',
                            icon: 'error',
                          });
                        } else {
                          // this.playGames();
                          this.speeddown2();
                        }
                      },
                    );
                  }}
                />
                <Image className="btn3" src={btn3} mode="heightFix" />
              </View>
            </View>
          </View>
          <View className="frequency">
            剩余抽奖次数：<Text className="frequencyNum">{frequencyNum}</Text>
          </View>
          <View className="notice">
            <Text className="notice-title">中奖公告</Text>
            <View className="notice-box">
              {winningAnnouncementList.length > 0 &&
                displayedAnnouncements.map((item, index) => {
                  return (
                    <View className="notice-box-record" key={index}>
                      {item.mobile.substring(0, 3) + '****' + item.mobile.substring(7)}
                      中了
                      <Text className="notice-box-red">{item.prizeContent}</Text>
                    </View>
                  );
                })}
            </View>
          </View>
          <View className="notice">
            <Text className="notice-title">活动规则</Text>
            <View className="notice-box">
              <RichText className="notice-box-info" nodes={activityRegulation}></RichText>
              {/* <View className="notice-box-info">{activityRegulation}</View> */}
            </View>
          </View>
        </ScrollView>
        <GetPrizes />
      </View>
    );
  }
}
